<script setup lang="ts">
  import { useGetReturnFactoryDetailGoodList } from '@/services/pages/return-factory/useReturnFactory'
  import { computed, h, PropType, ref } from 'vue'
  import UpdateGoodInfoModal from './UpdateGoodInfoModal.vue'
  import CheckGoodModal from './CheckGoodModal.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import LogisticsFillInModal from '../logistics-list/LogisticsFillInModal.vue'
  import SignForReceipt from '../logistics-list/SignForReceipt.vue'
  import _ from 'lodash'
  import { ElDivider, ElMessageBox, ElTable, ElTableColumn, TableInstance } from 'element-plus'
  import { useDetectCreate } from '@/services/pages/return-factory/useReturnFactory'
  import { useRouter } from 'vue-router'
  import ReturnLogisticsFillModal from '../logistics-list/ReturnLogisticsFillModal.vue'
  import CustomerReceiptConfirm from '../logistics-list/CustomerReceiptConfirm.vue'
  import videoCover from '@/assets/image/pages/order/new/video.png'
  import VideoPreview from '@/views/return-factory/repair/form/components/custom-info/VideoPreview.vue'
  import { repairReversePosting } from '@/api/return-factory'
  import HFilePreview from '@/components/common/file-preview/index.vue'

  const {
    loading: getReturnFactoryDetailGoodListLoading,
    goodList,
    getGoodList,
  } = useGetReturnFactoryDetailGoodList()
  const { form, create } = useDetectCreate()

  defineOptions({
    name: 'GoodListReturnFactoryDetail',
  })

  const props = defineProps({
    moduleCheckMethod: {
      type: Number as PropType<1 | 2>,
      default: () => 2,
    },
    detail: {
      type: Object as PropType<ReturnFactoryDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'select-good', value: Array<ReturnFactoryDetailGood>): void
  }>()

  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })
  const tableInstance = ref<TableInstance | null>(null)

  // 全局路由对象
  const router = useRouter()

  // 产品选择列表
  const selectedGoods = ref<Array<ReturnFactoryDetailGood>>([])

  // 视频预览链接列表
  const videoPreviewUrls = ref<Array<string>>([])

  // 预览视频索引
  const videoPreviewIndex = ref(0)

  // 预览视频弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 审核产品弹窗显示状态
  const checkGoodModalVisible = ref(false)

  // 表格图片列的列宽
  const tablePictureColumnWidth = computed(() => {
    const max = Math.max(...goodList.value.map((good) => good.images.length))
    return (max || 1) * 75
  })

  // 表格视频列的列宽
  const tableVideoColumnWidth = computed(() => {
    const max = Math.max(...goodList.value.map((good) => good.videoPaths.length))
    return (max || 1) * 75
  })

  // 修改产品信息弹窗显示状态
  const updateGoodInfoModalVisible = ref(false)

  // 当前正在编辑的产品清单id
  const currentEditGoodId = ref('')

  // 当前正在编辑的产品的序号
  const currentEditGoodNo = ref(1)

  // 填写物流弹窗显示状态
  const logisticsFillInModalVisible = ref(false)

  // 签收弹窗显示状态
  const signForReceiptModalVisible = ref(false)

  // 退回物流填写弹窗显示状态
  const returnLogisticsFillModalVisible = ref(false)

  // 确认公司签收弹窗显示状态
  const customerReceiptConfirmModalVisible = ref(false)

  /**
   * 详情点击事件
   */
  const handleDetailClick = (id: string, no: number) => {
    currentEditGoodId.value = id
    updateGoodInfoModalVisible.value = true
    currentEditGoodNo.value = no
  }

  /**
   * 产品选择事件
   * @param {Array<ReturnFactoryDetailGood>} goods - 产品列表
   */
  const handleSelectionChange = (goods: Array<ReturnFactoryDetailGood>) => {
    selectedGoods.value = goods
    emits('select-good', _.cloneDeep(goods))
  }

  /**
   * 审核点击事件
   */
  const onCheckClick = () => {
    if (props.moduleCheckMethod === 2 && selectedGoods.value.length === 0) {
      HMessageBox.error(infoTip.returnFactory.detail.checking_no_select_good)
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 0)) {
      HMessageBox.error('只能选择待审核的产品')
      return
    }

    checkGoodModalVisible.value = true
  }

  /**
   * 产品列表更新事件
   */
  const onUpdateGoodList = () => {
    // getList()
    emits('update')
  }

  /**
   * 获取产品列表
   */
  const getList = async () => {
    await getGoodList(props.detail.id)
  }

  /**
   * 填写物流点击事件
   */
  const onFillLogistics = () => {
    if (props.moduleCheckMethod === 2 && selectedGoods.value.length === 0) {
      HMessageBox.error(infoTip.returnFactory.detail.fill_logistics_no_select)
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 1)) {
      HMessageBox.error('只能选择待返厂的产品')
      return
    }

    selectedGoods.value = goodList.value
    logisticsFillInModalVisible.value = true
  }

  /**
   * 签收产品事件
   */
  const onSignForReceipt = () => {
    if (props.moduleCheckMethod === 1) {
      selectedGoods.value = goodList.value
    }

    if (props.moduleCheckMethod === 2 && selectedGoods.value.length === 0) {
      HMessageBox.error(infoTip.returnFactory.detail.fill_logistics_no_select)
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 2)) {
      HMessageBox.error('只能选择待签收的产品')
      return
    }

    signForReceiptModalVisible.value = true
  }

  /**
   * 生成检测单
   */
  const onDetectCreate = async () => {
    // if (props.detail.status === 4 && selectedGoods.value.length <= 0) {
    //   HMessageBox.error(infoTip.returnFactory.detail.create_detect_good_is_empty)
    //   return
    // }
    //
    // if (selectedGoods.value.some((item) => item.status !== 3)) {
    //   HMessageBox.error('只能选择待检测的产品')
    //   return
    // }

    form.value.repairId = props.detail.id
    form.value.repairGoodsIds = goodList.value.map((item) => item.id)
    const res = await create()
    if (res.code === 20000) {
      getList()
      emits('update')
      HMessage.success(infoTip.returnFactory.detail.create_detect_success)
      return
    }

    HMessageBox.error(res.message)
  }

  /**
   * 退回物流点击事件
   */
  const onReturnLogistics = () => {
    if ([5, 10].includes(props.detail.status)) {
      if (selectedGoods.value.length <= 0) {
        HMessageBox.error('请选择产品')
        return
      }

      if (selectedGoods.value.some((item) => ![5, 10].includes(item.status))) {
        HMessageBox.error('只能选择待寄回给公司的产品')
        return
      }
    }

    returnLogisticsFillModalVisible.value = true
  }

  /**
   * 确认公司签收
   */
  const onCustomerReceiptConfirm = () => {
    selectedGoods.value = _.cloneDeep(goodList.value).filter((item) => item.status === 6)

    if (selectedGoods.value.length <= 0) {
      HMessageBox.error('请选择产品')
      return
    }

    if (selectedGoods.value.some((item) => item.status !== 6)) {
      HMessageBox.error('只能选择待公司签收的产品')
      return
    }

    customerReceiptConfirmModalVisible.value = true
  }

  /**
   * 检测单号点击事件
   * @param id
   */
  const handleDetectNoClick = (id: string) => {
    router.push(`/return/factory/detect/detail/${id}`)
  }

  /**
   * 视频预览事件
   * @param {Number} index - 产品索引
   */
  const handlePreviewVideo = (index: number) => {
    videoPreviewUrls.value = goodList.value[index].videoPaths
    videoPreviewIndex.value = index
    videoPreviewModalVisible.value = true
  }

  const handleFillReturnLogisticsClick = (data: ReturnFactoryDetailGood) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(data, true)
      returnLogisticsFillModalVisible.value = true
    }
  }

  const handleReversePostingClick = () => {
    ElMessageBox({
      title: '提示',
      message: '确定要反过账吗?',
      type: 'warning',
      autofocus: false,
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          try {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            let errMsg = ''
            for (let i = 0; i < goodList.value.length; i++) {
              const _good = goodList.value[i]
              const res = await repairReversePosting(
                props.detail.id,
                _good.jsons.postingIdOnPostAtReturn,
                7,
              )
              if (res.data.code !== 20000) {
                errMsg = res.data.message
                break
              }
            }
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (!errMsg) {
              HMessage.success('操作成功')
              onUpdateGoodList()
              done()
              return
            }
            HMessageBox.error(errMsg)
            return
          } catch (error) {
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
          }
          return
        }

        done()
      },
    })
  }

  defineExpose({
    getList,
    goodList,
  })
</script>

<template>
  <div
    v-loading="getReturnFactoryDetailGoodListLoading"
    class="return-factory-detail-table-wrapper"
  >
    <div class="title-wrapper">
      <div class="text">产品详情</div>
      <h-plain-button
        v-if="props.detail.status === 1"
        v-permission="'retrunFactory_check'"
        :height="20"
        :padding-lr="6"
        type="warning"
        @click="onCheckClick"
      >
        审核
      </h-plain-button>
      <h-plain-button
        v-if="props.detail.status === 2 && props.detail.btnEventType === 1"
        v-permission="'retrunFactory_logistics'"
        :height="20"
        :padding-lr="6"
        @click="onFillLogistics"
      >
        填写返厂物流
      </h-plain-button>
      <h-plain-button
        v-if="props.detail.status === 3 && props.detail.btnEventType === 2"
        v-permission="'retrunFactory_sign'"
        :height="20"
        :padding-lr="6"
        @click="onSignForReceipt"
      >
        签收产品
      </h-plain-button>
      <h-plain-button
        v-if="props.detail.status === 4 && props.detail.btnEventType === 3"
        v-permission="'retrunFactory_detect'"
        :height="20"
        :padding-lr="6"
        @click="onDetectCreate"
      >
        生成检测单
      </h-plain-button>
      <h-plain-button
        v-if="props.detail.status === 5 || props.detail.status === 10"
        v-permission="'retrunFactory_returnLogistics'"
        :height="20"
        :padding-lr="6"
        @click="onReturnLogistics"
      >
        填写寄回物流
      </h-plain-button>
      <h-plain-button
        v-if="goodList.some((item) => item.status === 6)"
        v-permission="'retrunFactory_receiptConfirm'"
        :height="20"
        :padding-lr="6"
        @click="onCustomerReceiptConfirm"
      >
        待客户签收
      </h-plain-button>
      <h-plain-button
        v-if="[6, 10].includes(props.detail.status)"
        :height="20"
        :padding-lr="6"
        @click="handleReversePostingClick"
      >
        反过账
      </h-plain-button>
    </div>
    <div class="return-factory-detail-table">
      <el-table
        ref="tableInstance"
        :border="true"
        :data="goodList"
        stripe
        :tooltip-options="{ popperClass: 'table-cell-tooltip' }"
        :max-height="200"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择 -->
        <el-table-column
          v-if="props.detail.status === 10"
          width="50"
          fixed="left"
          type="selection"
          :align="'center'"
          :selectable="(row: ReturnFactoryDetailGood) => row.status === 10"
        />

        <!-- 序号 -->
        <el-table-column width="50" fixed="left" label="序号" type="index" :align="'center'" />

        <!-- 条码 -->
        <el-table-column width="120" label="条码" prop="code" show-overflow-tooltip />

        <template v-if="![1, 2, 3, 4].includes(props.detail.status)">
          <!-- 交货日期 -->
          <el-table-column
            v-if="
              goodList.some((item) => [3, 4].includes(Number(item.recommend))) &&
              [11, 6, 7].includes(props.detail.status)
            "
            width="120"
            label="交货日期"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{ row.jsons ? row.jsons.dateOfPostingAtSend : '' }}
            </template>
          </el-table-column>

          <!-- 退货单号 -->
          <el-table-column width="120" label="退货单号" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.jsons ? row.jsons.deliveryIDAtSyncSAPAtJudgeOfReturnType : '' }}
            </template>
          </el-table-column>

          <!-- 交货单号 -->
          <el-table-column
            v-if="
              goodList.some((item) => [3, 4].includes(Number(item.recommend))) &&
              [11, 6, 7].includes(props.detail.status)
            "
            width="120"
            label="交货单号"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{ row.jsons ? row.jsons.deliveryIDOnSaveCustomerReceiveAddr : '' }}
            </template>
          </el-table-column>

          <!-- 实收过账单号 -->
          <el-table-column width="120" label="实收过账单号" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.jsons ? row.jsons.postingIdOnPostAtReturn : '' }}
            </template>
          </el-table-column>

          <!-- 实发过账单号 -->
          <el-table-column
            v-if="
              goodList.some((item) => [3, 4].includes(Number(item.recommend))) &&
              [11, 6, 7].includes(props.detail.status)
            "
            width="120"
            label="实发过账单号"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{ row.jsons ? row.jsons.postingIdOnPostAtSend : '' }}
            </template>
          </el-table-column>
        </template>

        <!-- 产品类型 -->
        <!-- <el-table-column width="80" label="产品类型" prop="type" show-overflow-tooltip>
          <template #default="{ row }">{{ row.type === 1 ? '成品' : '配件' }}</template>
        </el-table-column> -->

        <!-- 产品编号 -->
        <el-table-column label="产品编号" prop="goodsCode" width="140" show-overflow-tooltip />

        <!-- 产品名称 -->
        <el-table-column label="产品名称" prop="goodsName" width="160" show-overflow-tooltip />

        <!-- 规格 -->
        <el-table-column label="规格" prop="goodsSpec" width="140" show-overflow-tooltip />

        <!-- 数量 -->
        <el-table-column label="数量" prop="qty" width="60" />

        <!-- 返厂产品问题 -->
        <el-table-column label="返厂产品问题" width="240" prop="descr" show-overflow-tooltip />

        <!-- 返厂图片 -->
        <el-table-column label="返厂图片" :width="tablePictureColumnWidth">
          <template #default="{ row }">
            <div class="image-list">
              <h-image
                v-for="(img, index) in row.images"
                :key="index"
                :show-del-btn="false"
                :src="img"
                :preview-src-list="row.images"
                :padding="2"
                :width="60"
                :height="37.5"
                :initial-index="index"
              />
            </div>
          </template>
        </el-table-column>

        <!-- 返厂视频 -->
        <el-table-column label="返厂视频" :width="tableVideoColumnWidth">
          <template #default="{ row }">
            <div class="image-list">
              <h-image
                v-for="(img, index) in row.videoPaths"
                :key="index"
                :show-del-btn="false"
                :is-show-img-preview="false"
                :src="videoCover"
                :padding="2"
                :width="60"
                :height="37.5"
                :initial-index="index"
                @preview="handlePreviewVideo(index)"
              />
            </div>
          </template>
        </el-table-column>

        <!-- 返厂附件 -->
        <el-table-column
          v-if="![1, 2].includes(props.detail.status)"
          label="返厂附件"
          width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <h-file-preview
              :file-url="row.sendBackLogisticsFile"
              :file-name="(row.sendBackLogisticsFile || '').split('/').pop()"
            />
          </template>
        </el-table-column>

        <!-- 检测附件 -->
        <el-table-column
          v-if="![1, 2, 3].includes(props.detail.status)"
          label="检测附件"
          width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <h-file-preview
              :file-url="row.checkResultFile"
              :file-name="(row.checkResultFile || '').split('/').pop()"
            />
          </template>
        </el-table-column>

        <!-- 处理方式 -->
        <!-- <el-table-column v-if="props.detail.status !== 1" label="处理方式" width="100">
          <template #default="{ row }">
            {{ row.handleMode === 0 ? '' : row.handleMode === 1 ? '确认返厂' : '无需返厂' }}
          </template>
        </el-table-column> -->

        <el-table-column v-if="![1, 2, 3, 4].includes(props.detail.status)" label="责任判定">
          <template #default="{ row }">
            <span v-if="Number(row.handleOpinion) === 1">公司责任</span>
            <span v-if="Number(row.handleOpinion) === 2">用户责任</span>
            <span v-if="Number(row.handleOpinion) === 3">维修责任</span>
            <span v-if="Number(row.handleOpinion) === 4">其他</span>
          </template>
        </el-table-column>

        <el-table-column v-if="![1, 2, 3, 4].includes(props.detail.status)" label="处理判定">
          <template #default="{ row }">
            <span v-if="Number(row.recommend) === 1">标准退货</span>
            <span v-if="Number(row.recommend) === 2">免费退货</span>
            <span v-if="Number(row.recommend) === 3">维修退货</span>
            <span v-if="Number(row.recommend) === 4">换货</span>
            <span v-if="Number(row.recommend) === 5">退货记录</span>
          </template>
        </el-table-column>

        <!-- 处理意见 -->
        <!-- <el-table-column
          v-if="props.detail.status !== 1"
          label="处理意见"
          prop="handleOpinion"
          width="140"
          show-overflow-tooltip
        /> -->

        <!-- 寄回物流名称 -->
        <el-table-column
          v-if="props.detail.status !== 1"
          label="寄回物流名称"
          prop="sendBackLogisticsName"
          width="140"
          show-overflow-tooltip
        />

        <!-- 寄回物流单号 -->
        <el-table-column
          v-if="props.detail.status !== 1"
          label="寄回物流单号"
          prop="sendBackLogisticsNo"
          width="160"
          show-overflow-tooltip
        />

        <!-- 寄出物流名称 -->
        <!-- <el-table-column
          label="寄出物流名称"
          prop="sendOutLogisticsName"
          width="140"
          show-overflow-tooltip
        /> -->

        <!-- 寄出物流单号 -->
        <!-- <el-table-column label="寄出物流单号" prop="sendOutLogisticsNo" width="160" /> -->

        <!-- 状态 -->
        <el-table-column label="状态" fixed="right" :align="'center'" width="120">
          <template #default="{ row }">
            <div class="flex_justify_center">
              <h-status v-if="row.status === 0" type="warning">待审核</h-status>
              <h-status v-if="row.status === 1" type="warning">待返厂</h-status>
              <h-status v-if="row.status === 2" type="warning">待签收</h-status>
              <h-status v-if="row.status === 3" type="warning">待检测</h-status>
              <h-status v-if="row.status === 4">处理中</h-status>
              <h-status v-if="row.status === 5" type="warning">待寄回公司</h-status>
              <h-status v-if="row.status === 6" type="warning">待客户签收</h-status>
              <h-status v-if="row.status === 7" type="success">已完成</h-status>
              <h-status v-if="row.status === 8" type="info">已取消</h-status>
              <h-status v-if="row.status === 9" type="warning">实收未过账</h-status>
              <h-status v-if="row.status === 10" type="warning">待发货</h-status>
              <h-status v-if="row.status === 11" type="warning">实发未过账</h-status>
            </div>
          </template>
        </el-table-column>

        <!-- 检测单号 -->
        <el-table-column
          v-if="goodList.every((item) => ![0, 1, 2, 3].includes(item.status))"
          label="检测单号"
          fixed="right"
          prop="repairCheckNo"
          column-key="repairCheckNo"
          width="100"
        >
          <template #default="{ row }">
            <h-link @click="handleDetectNoClick(row.repairCheckId)">
              {{ row.repairCheckNo }}
            </h-link>
          </template>
        </el-table-column>

        <!--操作-->
        <el-table-column label="操作" fixed="right" width="140">
          <template #default="{ row, $index }">
            <el-space :size="0" :spacer="spacer">
              <h-link
                v-permission="'retrunFactory_update'"
                @click="handleDetailClick(row.id, $index + 1)"
              >
                详情
              </h-link>
              <h-link v-if="row.status === 10" @click="handleFillReturnLogisticsClick(row)">
                填写寄回物流
              </h-link>
              <h-link v-else disabled>填写寄回物流</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <!--<div class="pagination">-->
      <!--  <el-pagination-->
      <!--    size="small"-->
      <!--    background-->
      <!--    layout="prev, pager, next"-->
      <!--    :total="total"-->
      <!--    :page-size="4"-->
      <!--    @current-change="handleCurrentChange"-->
      <!--  />-->
      <!--</div>-->
    </div>

    <!-- 更新产品信息弹窗 -->
    <update-good-info-modal
      v-model:visible="updateGoodInfoModalVisible"
      :good-id="currentEditGoodId"
      :serial-number="currentEditGoodNo"
      @update="onUpdateGoodList"
    />

    <!-- 审核产品弹窗 -->
    <check-good-modal
      v-model:visible="checkGoodModalVisible"
      :return-factory-id="props.detail.id"
      :check-method="props.moduleCheckMethod"
      :goods="selectedGoods"
      @check-success="onUpdateGoodList"
    />

    <!-- 物流填写弹窗 -->
    <logistics-fill-in-modal
      v-model:visible="logisticsFillInModalVisible"
      :check-method="props.moduleCheckMethod"
      :return-factory-id="props.detail.id"
      :selected-logistics-list="selectedGoods"
      @update="onUpdateGoodList"
    />

    <!-- 签收弹窗 -->
    <sign-for-receipt
      v-model:visible="signForReceiptModalVisible"
      :good-list="selectedGoods"
      :return-factory-id="props.detail.id"
      @update="onUpdateGoodList"
    />

    <!-- 退回物流填写弹窗 -->
    <return-logistics-fill-modal
      v-model:visible="returnLogisticsFillModalVisible"
      :repair-good-list="selectedGoods"
      :return-factory-id="props.detail.id"
      @update="onUpdateGoodList"
    />

    <!-- 代公司签收 -->
    <customer-receipt-confirm
      v-model:visible="customerReceiptConfirmModalVisible"
      :good-list="selectedGoods"
      :return-factory-id="props.detail.id"
      @update="onUpdateGoodList"
    />

    <video-preview
      v-model:visible="videoPreviewModalVisible"
      :video-list="videoPreviewUrls"
      :initial-index="videoPreviewIndex"
    />
  </div>
</template>

<style scoped lang="scss">
  :deep(.table-cell-tooltip) {
    max-width: 300px;
  }

  .return-factory-detail-table-wrapper {
    display: flex;
    flex-direction: column;
    row-gap: 6px;

    .title-wrapper {
      display: flex;
      column-gap: 5px;
      align-items: center;

      .text {
        padding-left: 6px;
        font-size: 12px;
        border-left: 3px solid $primaryColor;
        font-weight: bold;
      }
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }

  .image-list {
    display: flex;
    column-gap: 5px;
  }

  .pagination {
    margin-top: 6px;

    :deep(.el-pagination) {
      button {
        height: 24px !important;
      }

      .el-pager {
        li {
          height: 24px !important;
        }
      }
    }
  }
</style>
